/*
 * Copyright (C) 2009 Juan Alberto López Cavallotti
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package gui;


/*
 * MainWin.java
 * 
 * Created on 30/04/2009, 10:09:48
 */



import filesystem.FileSystemListener;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author juan
 */
public class MainWin extends javax.swing.JFrame implements FileSystemListener {

    private TrayIcon trayIcon;
    private PopupMenu trayIconPopup;

    /** Creates new form MainWin */
    public MainWin() {
        initComponents();
        //colocar en la bandeja del sistema
        putInTray();
    }

    private void exitApp() {
        System.exit(0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaSalida = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TeamWork FileSync");

        jButton1.setText("Exit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        areaSalida.setColumns(20);
        areaSalida.setEditable(false);
        areaSalida.setLineWrap(true);
        areaSalida.setRows(5);
        jScrollPane1.setViewportView(areaSalida);

        jButton2.setText("Settings");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void initiatePopupMenu() {

        trayIconPopup = new PopupMenu(getTitle());

        //el item de las configuraciones
        MenuItem itemSet = new MenuItem("Settings");
        //el item de salir
        MenuItem itemExit = new MenuItem("Exit");

        itemSet.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                showSettings();
            }
        });

        itemExit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                exitApp();
            }
        });

        trayIconPopup.add(itemSet);
        trayIconPopup.addSeparator();
        trayIconPopup.add(itemExit);

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        exitApp();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        showSettings();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainWin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea areaSalida;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    public void fileAdded(File f) {
        areaSalida.append("Agregado: "+f.getPath()+"\n");
    }

    public void fileDeleted(String f) {
        areaSalida.append("Borrado: "+f+"\n");
    }

    public void fileModified(File f) {

        if (!f.isDirectory())
            areaSalida.append("Actualizado: "+f.getPath()+"\n");
    }

    private void putInTray() {

        try {
            if (!SystemTray.isSupported()) {
                return; //no soportado
            }
            Image icono = Toolkit.getDefaultToolkit().getImage("images/icon.png");

            initiatePopupMenu();
            

            if (icono == null) {
                throw new Error("No encontre el icono");
            }
            trayIcon = new TrayIcon(icono, getTitle());
            trayIcon.setImageAutoSize(true);
            trayIcon.addMouseListener(new EscuchaMouseIcono());
            trayIcon.setPopupMenu(trayIconPopup);

            SystemTray.getSystemTray().add(trayIcon);
        } catch (AWTException ex) {
            Logger.getLogger(MainWin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    @Override
    public void dispose() {
        setVisible(false);
    }

    private void showSettings() {
        ParametersGui gui = new ParametersGui();
        gui.setVisible(true);
    }

    private class EscuchaMouseIcono implements MouseListener {
        
        public void mouseClicked(MouseEvent e) {
            if (MainWin.this.isVisible()) {
                MainWin.this.setVisible(false);
            } else {
                MainWin.this.setVisible(true);
            }
        }

        public void mousePressed(MouseEvent e) {
            
        }

        public void mouseReleased(MouseEvent e) {
            
        }

        public void mouseEntered(MouseEvent e) {
            
        }

        public void mouseExited(MouseEvent e) {
            
        }
    }

}
